<template>
  <div class="login-box">
    <div class="login-form-wrapper">
      <!-- 登录Arco Design Pro -->
      <div class="login-form-title">{{ $t('欢迎来到隐厨后台管理平台') }}</div>
      <!-- <div class="login-form-sub-title">{{ $t('login.form.title') }}</div> -->
      <div class="login-form-error-msg">{{ errorMessage }}</div>
      <a-form ref="loginForm" :model="userInfo" class="login-form" layout="vertical" @submit="handleSubmit">
        <a-form-item field="username" :rules="[{ required: true, message: $t('login.form.userName.errMsg') }]"
          :validate-trigger="['change', 'blur']" hide-label>
          <a-input v-model="userInfo.username" :placeholder="$t('login.form.userName.placeholder')">
            <template #prefix>
              <icon-user />
            </template>
          </a-input>
        </a-form-item>
        <a-form-item field="password" :rules="[{ required: true, message: $t('login.form.password.errMsg') }]"
          :validate-trigger="['change', 'blur']" hide-label>
          <a-input-password v-model="userInfo.password" :placeholder="$t('login.form.password.placeholder')" allow-clear>
            <template #prefix>
              <icon-lock />
            </template>
          </a-input-password>
        </a-form-item>

        <a-space :size="16" direction="vertical">
          <div class="login-form-password-actions">
            <a-checkbox checked="rememberPassword" :model-value="loginConfig.rememberPassword"
              @change="(setRememberPassword as any)">
              {{ $t('login.form.rememberPassword') }}
            </a-checkbox>
            <a-link @click="fixPassword">{{ $t('修改密码') }}</a-link>
          </div>
          <a-button type="primary" html-type="submit" long :loading="loading">
            {{ $t('login.form.login') }}
          </a-button>
        </a-space>
      </a-form>
    </div>
    <!-- 新增的扫码登录按钮 -->
    <div class="qr-code-login-btn" @click="handleQrCodeLogin">
      {{ $t('扫码登录') }}
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive } from 'vue';
import { useRouter } from 'vue-router';
import { Message } from '@arco-design/web-vue';
import { ValidatedError } from '@arco-design/web-vue/es/form/interface';
import { useI18n } from 'vue-i18n';
import { useStorage } from '@vueuse/core';

import useLoading from '@/hooks/loading';

import { loginUser } from '@/api/login';

import { useAppStore, useUserStore } from '@/store';
import {setTokenU, clearToken, setToken} from '@/utils/auth';
const userStore = useUserStore();
const authCodeUrl = ref(import.meta.env.VITE_API_BASE_URL + 'Verify/user/getVerify');
const clickAuthCodeImage = () => {
  authCodeUrl.value = import.meta.env.VITE_API_BASE_URL + 'Verify/user/getVerify?' + Date.now()
};
const router = useRouter();
const { t } = useI18n();
const errorMessage = ref('');
const { loading, setLoading } = useLoading();

const loginConfig = useStorage('login-config', {
  rememberPassword: true,
  username: 'lx',
  password: '123',
});
const userInfo = reactive({
  username: loginConfig.value.username,
  password: loginConfig.value.password,
  code: "",
  rememberme: 0
});

const handleSubmit = async ({
  errors,
  values,
}: {
  errors: Record<string, ValidatedError> | undefined;
  values: Record<string, any>;
}) => {
  loginUser(
    userInfo.username,
    userInfo.password
  ).then((res) => {
    const { redirect, ...othersQuery } = router.currentRoute.value.query;
    if (res.data.code == 500) {
      console.log("登录失败");
      Message.error(t('用户名或密码错误，请重新输入'));
    } else {
      userStore.login();
      router.push({
        name: (redirect as string) || 'Workplace',
        query: {
          ...othersQuery,
        },
      });
      console.log(res.data);
      // 创建配置对象
      const config = {
        userid: res.data.data.userId,
        username: res.data.data.userName,
        userbid: res.data.data.userBid
      };
      // 将对象转换为 JSON 字符串并存储到本地存储
      localStorage.setItem('userInfo', JSON.stringify(config));
      // 从本地存储读取数据并转换回对象
      setToken(res.data.data.userToken)
      Message.success(t('login.form.login.success'));
      console.log("登陆成功");
    }
  });
};

const setRememberPassword = (value: boolean) => {
  loginConfig.value.rememberPassword = value;
};

const fixPassword = () => {
  router.push({
    name: 'fixPassword',
  });
};

// 新增的扫码登录处理函数
const handleQrCodeLogin = () => {
  router.push({
    name: 'saoMa',
  });
  // 这里可以添加实际的扫码登录逻辑，比如跳转到扫码页面等
};
</script>

<style lang="less" scoped>
.login-form {
  &-wrapper {
    width: 320px;
  }

  &-title {
    color: var(--color-text-1);
    font-weight: 500;
    font-size: 24px;
    line-height: 32px;
  }

  &-sub-title {
    color: var(--color-text-3);
    font-size: 16px;
    line-height: 24px;
  }

  &-error-msg {
    height: 32px;
    color: rgb(var(--red-6));
    line-height: 32px;
  }

  &-password-actions {
    display: flex;
    justify-content: space-between;
  }

  &-register-btn {
    color: var(--color-text-3) !important;
  }
}

@font-face {
  font-family: "iconfont";
  /* Project id 3606608 */
  src: url('//at.alicdn.com/t/c/font_3606608_y4iw4xdogic.woff2?t=1661252460893') format('woff2'),
    url('//at.alicdn.com/t/c/font_3606608_y4iw4xdogic.woff?t=1661252460893') format('woff'),
    url('//at.alicdn.com/t/c/font_3606608_y4iw4xdogic.ttf?t=1661252460893') format('truetype');
}

.iconfont {
  font-family: "iconfont" !important;
  font-size: 16px;
  font-style: normal;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
}

.icon-yanzhengyanzhengma:before {
  content: "\e624";
}

.identifyingCode {
  width: 170px;
}

.identifyingCode-img {
  margin-left: 40px;
}

.login-form-title {
  color: rgb(230, 230, 238);
  font-size: 21px;
  text-align: center;
}

.login-box {
  width: 520px;
  height: 380px;
  display: flex;
  justify-content: center;
  align-items: center;
  // background-color: rgba(44, 58, 188, 0.5);
  box-shadow: 0 0 4px 3px #a2cbf7;
  // border: 1px solid rgb(13, 76, 127);
  border-radius: 10px;
  position: relative;
}

// 新增的扫码登录按钮样式
.qr-code-login-btn {
  position: absolute;
  top: 10px;
  right: 10px;
  color: #0575ef;
  cursor: pointer;
}

::v-deep .arco-input-wrapper {
  background-color: rgba(253, 253, 253, 0.9);
  color: rgb(59, 62, 62);
  border-radius: 7px;
}

.arco-btn-primary {
  background-color: #0575ef;
}

// .login-form-wrapper {}
</style>